#include "Friend.h"

const char Friend::className[] = "Friend";

#define method(class, name) {#name, &class::name}

Lunar<Friend>::RegType Friend::methods[] = {
	method(Friend, load),
	method(Friend, setClueID),
	method(Friend, setClothID),
};

int Friend::load(lua_State* L) {
	Character::load(L);

	// Declare instance of class to record state of keyboard
	m_pkeyState = new KeyboardState();

	// Set up the tank update callback
	//  pass the constructor a pointer to our tank input device state
	//  that we declared above.
	m_ptransform->setUpdateCallback(new FriendActionCallback(m_pkeyState, this));

	// The constructor for our event handler also gets a pointer to
	//   our tank input device state instance
	KeyboardEventHandler* friendEventHandler = new KeyboardEventHandler(m_pkeyState);

	// Add our event handler to the list
	Engine::getInstance().getViewer().addEventHandler(friendEventHandler);

	return 0;
}

int Friend::setClueID(lua_State* L) {
	int nbArgs = lua_gettop(L);
	if (nbArgs == 1 && lua_isnumber(L,1)) {
		m_iclueID = lua_tonumber(L,1);
		return 0;
	}
	return -1;
}

int Friend::setClothID(lua_State* L) {
	int nbArgs = lua_gettop(L);
	if (nbArgs == 1 && lua_isnumber(L,1)) {
		m_iclothID = lua_tonumber(L,1);
		return 0;
	}
	return -1;
}

void FriendActionCallback::operator()(osg::Node* node, osg::NodeVisitor* nv) {
	osg::PositionAttitudeTransform* pat = dynamic_cast<osg::PositionAttitudeTransform*> (node);
	if(pat) {
		if ((m_pkeyState->m_key == osgGA::GUIEventAdapter::KEY_Space)&&(m_pkeyState->m_keydown)) {
			osg::Vec3d pos = pat->getPosition();
			osg::Vec3d player = StageManager::getInstance().getCurrentStage()->getPlayer()->getPosition();
			float dist = (pos-player).length();

			if(dist < 4.) {
				// If friend is walking, stop him
				if(!m_pfriend->getBrain()->getDialog()->isDialogOver()) {
					m_pfriend->getBrain()->setVelocity(Brain::STOP);
					m_pfriend->getBrain()->getDialog()->playDialog(m_pfriend->getClueID());
				}
				// If friend is stopped, restart his walk
				else if((m_pfriend->getBrain()->getVelocity() == Brain::STOP)&&(m_pfriend->getBrain()->getDialog()->isDialogOver())) {
					m_pfriend->getBrain()->setVelocity(Brain::NORMAL);
					m_pfriend->getBrain()->getDialog()->stopDialog();
				}
				
				m_pkeyState->m_keydown = false;
			}
		}
	}
	traverse(node, nv); 
}